﻿(function ($, undefined) {

    $.widget("ui.colorpicker", {
        options: {
            colors: [
                "#D9E027",
                "#8CC642",
                "#006837",
                "#03A99D",
                "#29AAE2",
                "#1072BA",
                "#673092",
                "#9D1F60",
                "#D61D5D",
                "#C7B399",
                "#554841",
                "#A57C52",
                "#603A17",
                "#C1272D",
                "#F15D27",
                "#FBB03B"
            ],
            template: "<div class='color-item'><div class='inner'></div></div>"
        },

        _create: function () {
            var $this = this;
            var element = this.element;
            $.each(this.options.colors, function (index, value) {
                $this._createColor(index, value);
            });

            element.append("<div style='clear:both;'></div>");
        },

        destroy: function () {
        },

        _createColor: function (index, code) {
            var $this = this;
            var element = this.element;

            var colorItem = $(this.options.template)
                    .attr("id", "coloritem_" + index)                    
                    .attr("value", index).appendTo(element)
                    .click(function () { $this.selectIndex(index); });
            
            colorItem.find(".inner").css("background-color", code);
        },

        select: function (code) {
            var index = $.inArray(code, this.options.colors);
            if (index >= 0) {
                this.selectIndex(index);
            }
        },

        selectIndex: function (index) {
            if (index < 0 || index >= this.options.colors.length) return;

            // deselect the currently selected item, if any
            var currentSelected = this.element.attr("value");
            if (currentSelected != undefined && currentSelected >= 0) {
                this.element.find("#coloritem_" + currentSelected).removeClass("color-item-selected");
            }
            
            this.element.find("#coloritem_" + index).addClass("color-item-selected");
            this.element.attr("value", index);
        },

        getSelectedValue: function () {
            return this.options.colors[this.element.attr("value")];
        }
    });

    $.extend($.ui.colorpicker, {
        version: "0.1.0"
    });

})(jQuery);